<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<cl-add-btn />
			<!-- 关键字搜索 -->
			<cl-search-key placeholder="搜索昵称" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table" />
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert" />
		<!-- 表单 -->
		<cl-form ref="FormRef">
			<template #slot-backpack_1_goods="{ scope }">
				<div class="cart">
					<el-form-item
						v-for="(item, index) in scope.backpack_1_goods"
						:key="index"
						:label="`物品${index + 1}`"
						:prop="`backpack_1_goods.${index}.gid`"
						:rules="{
							message: `请选择物品${index + 1}`,
							required: true
						}"
					>
						<div class="row">
							<!-- 输入框 -->
							<cl-select
								:options="goodsList"
								:placeholder="`请选择物品${index + 1}`"
								v-model="item.gid"
							/>
							<el-input-number v-model="item.num" style="margin-left: 20px" />

							<!-- 删除行 -->
							<el-icon @click="rowDel(index, 'backpack_1_goods')">
								<Delete />
							</el-icon>
						</div>
						<!-- 添加行 -->
					</el-form-item>
					<el-row type="flex" justify="end">
						<el-button @click="rowAdd('backpack_1_goods')">添加物品</el-button>
					</el-row>
				</div>
			</template>
			<template #slot-backpack_2_goods="{ scope }">
				<div class="cart">
					<el-form-item
						v-for="(item, index) in scope.backpack_2_goods"
						:key="index"
						:label="`物品${index + 1}`"
						:prop="`backpack_2_goods.${index}.gid`"
						:rules="{
							message: `请选择物品${index + 1}`,
							required: true
						}"
					>
						<div class="row">
							<!-- 输入框 -->
							<cl-select
								:options="goodsList"
								:placeholder="`请选择物品${index + 1}`"
								v-model="item.gid"
							/>
							<el-input-number v-model="item.num" style="margin-left: 20px" />

							<!-- 删除行 -->
							<el-icon @click="rowDel(index, 'backpack_2_goods')">
								<Delete />
							</el-icon>
						</div>
						<!-- 添加行 -->
					</el-form-item>
					<el-row type="flex" justify="end">
						<el-button @click="rowAdd('backpack_2_goods')">添加物品</el-button>
					</el-row>
				</div>
			</template>
		</cl-form>
	</cl-crud>
</template>

<script lang="ts" name="user-list" setup>
import { useCrud, useTable, useUpsert } from "@cool-vue/crud";
import { useCool } from "/@/cool";
import { reactive, ref, onMounted } from "vue";
import { Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
const FormRef = ref();
const raceList: any = ref([]);
const sectList: any = ref([]);
const tagList: any = ref([]);
const goodsList: any = ref([]);
const { service } = useCool();
// 背包数量
const backpackNum: any = ref(2);
const backpackList = Array.from({ length: backpackNum.value }, (val, i) => ({
	label: `背包${i + 1}`,
	value: `backpack_${i + 1}`
}));
// cl-table
const Table = useTable({
	columns: [
		{
			label: "昵称",
			prop: "nickName",
			minWidth: 150
		},
		{
			label: "头像",
			prop: "avatarUrl",
			minWidth: 100,
			component: {
				name: "cl-avatar"
			}
		},
		{
			label: "金币",
			prop: "gold",
			minWidth: 150
		},
		{
			label: "种族",
			prop: "raceId",
			minWidth: 150,
			dict: raceList
		},
		{
			label: "门派",
			prop: "sectId",
			minWidth: 150,
			dict: sectList
		},
		{
			label: "标签",
			prop: "tagIds",
			minWidth: 150,
			dict: tagList
		},

		{
			label: "创建时间",
			prop: "createTime",
			sortable: "desc",
			minWidth: 160
		},
		{
			label: "操作",
			type: "op",
			width: 400,
			buttons: [
				"edit",
				"delete",
				{
					label: "背包",
					type: "info",
					async onClick({ scope }) {
						// scope行数据
						// 获取背包数据
						const goodsItemsList = await service.user.data.getGoodsItems({
							uid: scope.row.id
						});
						const newGoodsItemsList = goodsItemsList.reduce((pre, val) => {
							const { backpack, id, num, gid, uid } = val;
							if (!pre[backpack]) {
								pre[backpack] = [];
							}
							pre[backpack].push({
								id,
								num,
								gid,
								uid
							});
							return pre;
						}, {});
						FormRef.value?.open({
							title: "分组显示",
							items: [
								{
									//【很重要】必须为 tabs
									type: "tabs",
									props: {
										// 分组样式
										type: "card",
										// 分组列表，必须是 { label, value } 的数组格式
										labels: backpackList
									}
								},
								...backpackList.map((item) => {
									return {
										group: item.value, // 标识
										label: "",
										prop: `${item.value}_goods`,
										// required: true,
										value: newGoodsItemsList[`${item.value}_goods`] || [],
										component: {
											name: `slot-${item.value}_goods`
										}
									};
								})
							],
							on: {
								//【提示】当第一组验证通过后，会自动切换到下一组展示，直到全部通过才可提交
								submit(data, { close }) {
									service.user.data
										.setGoodsItems({
											data: Object.entries(data)
												.map((item: any) => {
													const [key, val] = item;
													return val.map((v) => {
														return {
															backpack: key,
															uid: scope.row.id,
															gid: v.gid,
															num: v.num,
															id: v.id
														};
													});
												})
												.flat()
										})
										.then((res) => {
											ElMessage.success("更新成功");
											close();
										});
								}
							}
						});
					}
				},
				{
					label: "日志",
					type: "info",
					onClick({ scope }) {
						// scope行数据
						console.log(scope);
						ElMessage.info("我是用户日志");
					}
				}
			]
		}
	]
});

// cl-upsert
const Upsert = useUpsert({
	dialog: {
		width: "600px"
	},
	items: [
		{
			prop: "avatarUrl",
			label: "头像",
			// required: true,
			component: { name: "cl-upload" }
		},
		{
			prop: "nickName",
			label: "昵称",
			component: { name: "el-input" },
			required: true
		},
		{
			prop: "raceId",
			label: "种族",
			component: {
				name: "el-select",
				props: {
					filterable: true,
					async onChange(val) {
						const sect = await service.user.sect.list({
							raceId: val
						});
						Upsert.value?.setOptions(
							"sectId",
							sect.map((item) => ({ value: item.id, label: item.name }))
						);
						Upsert.value?.resetFields("sectId");
					}
				}
			},
			required: true
		},
		{
			prop: "sectId",
			label: "门派",
			component: { name: "el-select", props: { filterable: true } },
			required: true
		},
		{
			prop: "tagIds",
			label: "标签",
			component: {
				name: "el-select",
				options: [],
				props: {
					filterable: true,
					multiple: true
				}
			},
			required: true,
			hook: {
				bind: ["split"],
				submit: ["join"]
			}
		}
	],
	// 弹窗打开后，已经得到了表单数据
	async onOpened(data) {
		// 判定是否编辑模式
		if (Upsert.value?.mode == "update") {
			const sect = await service.user.sect.list({
				raceId: data.raceId
			});
			Upsert.value?.setOptions(
				"sectId",
				sect.map((item) => ({ value: item.id, label: item.name }))
			);
		}
		Upsert.value?.setOptions("tagIds", tagList);
		Upsert.value?.setOptions("raceId", raceList);
	}
});
function rowAdd(key) {
	FormRef.value?.form[key].push({
		gid: null,
		num: 0
	});
}
function rowDel(index, key) {
	FormRef.value?.form[key].splice(index, 1);
}
// cl-crud
const Crud = useCrud(
	{
		service: service.user.data
	},
	(app) => {
		app.refresh();
	}
);
onMounted(() => {
	service.user.race.list().then((res) => {
		raceList.value = res.map((item) => ({ value: item.id, label: item.name }));
	});
	service.user.tag.list().then((res) => {
		tagList.value = res.map((item) => ({ value: item.id + "", label: item.name }));
	});
	service.user.sect.list().then((res) => {
		sectList.value = res.map((item) => ({ value: item.id, label: item.name }));
	});
	service.user.goods.list().then((res) => {
		goodsList.value = res.map((item) => ({ value: item.id, label: item.name }));
	});
});
</script>

<style lang="scss" scoped>
.row {
	display: flex;
	align-items: center;

	.el-input {
		flex: 1;
		margin-right: 10px;
	}

	.el-icon {
		cursor: pointer;

		&:hover {
			color: red;
		}
	}
}
</style>
